<!-- 笔记左侧目录，约定最大存在 3 级目录 -->
<template>
  <div class="flex flex-col">
    <a class="block text-2xl mb-6 font-bold" :href="getHref()">笔记</a>
    <div v-for="(item, index) in list" :key="index" class="w-full">
      <div
        v-if="item.children?.length"
        class="flex items-center justify-between w-full cursor-pointer"
        @click="handleToggle(item.text)"
      >
        <div class="text-lg/[3rem]">
          {{ item.text }}
        </div>
        <div
          class="arrow-icon text-xl"
          :style="{
            transform: `rotate(${
              expandCollection.includes(item.text.toLowerCase()) ? 90 : 0
            }deg)`,
          }"
        >
          <Icon icon="mdi:chevron-right" />
        </div>
      </div>
      <!-- 二级目录 -->
      <div
        v-if="
          item.children?.length &&
          expandCollection.includes(item.text.toLowerCase())
        "
        class="pl-4"
      >
        <div
          v-for="(child, i) in item.children"
          :key="i"
          class="block text-base/[2.5rem]"
          :class="{ 'title-active': child.href.endsWith(currentRoute) }"
        >
          <div
            v-if="child.children?.length"
            class="flex items-center justify-between w-full cursor-pointer"
            @click="handleToggle(`${item.text}/${child.text}`)"
          >
            <div class="text-base/[2.5rem]" @click="handleTitle(child, $event)">
              {{ child.text }}
            </div>
            <div
              class="arrow-icon text-xl"
              :style="{
                transform: `rotate(${
                  expandCollection.includes(
                    `${item.text.toLowerCase()}/${child.text.toLowerCase()}`
                  )
                    ? 90
                    : 0
                }deg)`,
              }"
            >
              <Icon icon="mdi:chevron-right" />
            </div>
          </div>
          <a v-else :href="getHref(child.href)">{{ child.text }}</a>
          <div
            v-if="
              child.children?.length &&
              expandCollection.includes(
                `${item.text.toLowerCase()}/${child.text.toLowerCase()}`
              )
            "
            class="pl-4"
          >
            <!-- 三级目录 -->
            <a
              v-for="(subChild, j) in child.children"
              :key="j"
              class="block text-base/[2.5rem] text-gray-700"
              :class="{ 'title-active': subChild.href.endsWith(currentRoute) }"
              :href="getHref(subChild.href)"
            >
              {{ subChild.text }}
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, nextTick, onMounted, ref } from "vue";
import { Icon } from "@iconify/vue";

interface DocListData {
  text: string;
  href: string;
  children?: DocListData[];
}

const props = defineProps<{
  list: DocListData[];
  currentRoute: string; // 当前激活的路由
}>();

const expandCollection = ref([""]); // 当前展开的集合

// 切换展开折叠状态
function handleToggle(title: string) {
  title = title.toLowerCase();
  if (expandCollection.value.includes(title)) {
    expandCollection.value = expandCollection.value.filter((i) => i !== title);
  } else {
    expandCollection.value.push(title);
  }
  // 缓存到 localStorage 中
  localStorage.setItem(
    "expandCollection",
    JSON.stringify(expandCollection.value)
  );
}

// 拼接访问链接
function getHref(href?: string) {
  if (!href) return `/article`;
  return `/article/${href}`;
}

// 点击标题
function handleTitle(item: DocListData, e: MouseEvent) {
  if (item.href !== "#") {
    e.stopPropagation();
    window.location.href = getHref(item.href);
  }
}

onMounted(() => {
  // 当前激活的路由
  const routeArr = props.currentRoute.split("/");
  // 获取展开的目录，从 localStorage 中获取
  const expandCollectionStr = localStorage.getItem("expandCollection");
  if (expandCollectionStr) {
    const localExpand = JSON.parse(expandCollectionStr);
    if (localExpand.length) {
      expandCollection.value = localExpand;
    }
  }
  if (routeArr.length === 2) {
    expandCollection.value.push(routeArr[0]);
  }
  if (routeArr.length === 3) {
    expandCollection.value.push(routeArr[0], `${routeArr[0]}/${routeArr[1]}`);
  }
  // 页面加载完毕的时候滚动到高亮激活位置
  nextTick(() => {
    const activeTitle = document.querySelector(".title-active");
    if (activeTitle) {
      activeTitle.scrollIntoView({ behavior: "smooth", block: "center" });
    }
  });
});
</script>

<style lang="scss" scoped>
.arrow-icon {
  transition: transform 0.3s ease;
}

.title-active {
  @apply text-primary;
}
</style>
